<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <div>
        <!-- layout布局 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-input
                placeholder="请输入内容"
                v-model="userInfo.query"
                clearable
                @clear="getUserInfo"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="getUserInfo"
                ></el-button>
              </el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-button type="primary" @click="dialogVisible = true"
                >添加用户</el-button
              >
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 用户列表区域 -->
    <el-table :data="userList" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column label="状态">
        <!-- 通过scope.row可以访问列的数据 -->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="userActiveChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- 操作详情 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteUser(scope.row.id)"
          ></el-button>
          <el-tooltip
            effect="dark"
            content="分配角色"
            placement="top"
            :enterable="false"
          >
            <el-button
              @click="showRoledialg(scope.row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页显示 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="userInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 新增弹窗消息 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改弹窗消息 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色dialog -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="clearRole"
    >
      <div>
        <p>用户名称：{{ this.userData.username }}</p>
        <p>角色名称：{{ this.userData.role_name }}</p>
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleinfo(selectRoleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "User",
  data() {
    //自定义校验规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱是否合法
      const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      userInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 添加信息弹窗状态
      dialogVisible: false,
      // 修改信息弹窗状态
      editDialogVisible: false,
      //分配角色dialog
      roleDialogVisible: false,
      //保存用户info数据
      userData: "",
      //所有角色的列表
      roleList: "",
      //select展示的数据下拉菜单
      selectRoleId: "",
      // 用户添加提交对象
      addForm: {
        username: "",
        password: "",
        mobile: "",
        email: ""
      },
      //查询到的用户信息对象
      editForm: {
        username: "",
        password: "",
        mobile: "",
        email: ""
      },
      // 新增用户验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名!", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码!", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱!", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号码!", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ]
      },
      // 修改用户验证规则对象
      editFormRules: {
        username: [
          { required: true, message: "请输入用户名!", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码!", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱!", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号码!", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    //渲染用户信息
    async getUserInfo() {
      const { data: res } = await this.$http.get("users", {
        params: this.userInfo
      });
      if (res.meta.status !== 200) return;
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log(res);
    },
    handleSizeChange(newSize) {
      this.userInfo.pagesize = newSize;
      this.getUserInfo();
    },
    handleCurrentChange(newPage) {
      this.userInfo.pagenum = newPage;
      this.getUserInfo();
    },
    // 修改用户状态
    async userActiveChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("修改状态失败!");
      }
      this.$message.success("修改状态成功!");
    },
    //监听添加用户框,关闭事件
    addClose() {
      //添加用户
      this.$refs.addFormRef.resetFields();
      //修改用户
      // this.$refs.editFormRef.resetFields();
    },
    //监听修改用户框,关闭时间
    editClose() {
      this.$refs.editFormRef.resetFields();
    },
    //确定添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post("users", this.addForm);
          if (res.meta.status == 201) {
            this.$message.success("添加用户成功!");
            //将消息框关闭
            this.dialogVisible = false;
            // 刷新用户
            this.getUserInfo();
          } else {
            this.$message.error("添加用户失败!");
          }
        } else {
          return;
        }
      });
    },
    // 确定修改用户
    EditUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            { email: this.editForm.email, mobile: this.editForm.mobile }
          );
          if (res.meta.status == 200) {
            //将消息框关闭
            this.editDialogVisible = false;
            // 刷新用户
            this.getUserInfo();
            // 提示信息
            this.$message.success("修改用户成功!");
          } else {
            this.$message.error("更新用户失败!");
          }
        } else {
          return;
        }
      });
    },
    async showEditDialog(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status == 200) {
        this.editForm = res.data;
      } else {
        return;
      }
      console.log(id);
    },
    // 根据id删除用户信息
    async deleteUser(id) {
      const confirmRlust = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(confirmRlust);
      //如果用户点了确定泽返回字符串confirm,选择了取消返回字符串cancel
      if (confirmRlust === "confirm") {
        const { data: res } = await this.$http.delete("users/" + id);
        if (res.meta.status == 200) {
          this.$message.success("删除用户成功!");
          this.getUserInfo();
        } else {
          this.$message.error("删除用户失败!");
          this.getUserInfo();
        }
      } else {
        this.$message.info("取消了删除!");
      }
    },
    // 显示分配角色的dialog
    async showRoledialg(userInfo) {
      this.userData = userInfo;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status == 200) {
        this.roleList = res.data;
      }
      this.roleDialogVisible = true;
    },
    // 保存角色修改信息
    async saveRoleinfo(selectRoleId) {
      if (!selectRoleId) {
        this.$message.error("请选择角色！");
      } else {
        const { data: res } = await this.$http.put(
          `users/${this.userData.id}/role`,
          {
            rid: selectRoleId
          }
        );
        if (res.meta.status == 200) {
          this.$message.success("设置角色成功！");
          this.roleDialogVisible = false;
          this.getUserInfo();
        } else {
          this.$message.error("设置角色失败！");
        }
      }
    },
    // 分配角色dialog关闭清理界面
    clearRole() {
      this.selectRoleId = "";
      this.userData = {};
    }
  },
  components: {},
  computed: {},
  beforeMount() {},
  mounted() {},
  watch: {}
};
</script>
<style lang="less" scoped></style>
